import { defineStore } from "pinia";
import {
  createInforArticle,
  deleteInforArticle,
  fetchAllInforArticles,
  updateInforArticle,
  fetchInforArticle,
} from "@/api/inforemation/artcile";
import type { IInforArticle } from "@/api/inforemation/artcile";
import { ref } from "vue";

export const useInforArticleStore = defineStore("inforArticle", () => {
  const articles = ref<IInforArticle[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  // 获取所有健康科普文章
  const getAllArticles = async () => {
    try {
      loading.value = true;
      error.value = null;
      const res = await fetchAllInforArticles();
      articles.value = res.data;
      return res.data;
    } catch (err) {
      error.value = "获取健康科普文章列表失败";
      console.error("获取健康科普文章列表失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 新增健康科普文章
  const addArticle = async (data: IInforArticle) => {
    try {
      loading.value = true;
      await createInforArticle(data);
      await getAllArticles();
    } catch (err) {
      console.error("新增健康科普文章失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 更新健康科普文章
  const editArticle = async (data: IInforArticle) => {
    try {
      loading.value = true;
      await updateInforArticle(data);
      await getAllArticles();
    } catch (err) {
      console.error("更新健康科普文章失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 删除健康科普文章
  const removeArticle = async (id: number | string) => {
    try {
      loading.value = true;
      await deleteInforArticle(id);
      await getAllArticles();
    } catch (err) {
      console.error("删除健康科普文章失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  //根据id查询文章
  const getArticleById = async (id: number | string) => {
    try {
      loading.value = true;
      const res = await fetchInforArticle(id);
      return res.data;
    } catch (err) {
      console.error("查询健康科普文章失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  }

  return {
    articles,
    loading,
    error,
    getAllArticles,
    addArticle,
    editArticle,
    removeArticle,
    getArticleById,
  };
});